﻿using System;
using System.Web;
using System.Web.UI.WebControls;

namespace Malu.WebTemplates
{
    public class Pager : System.Web.UI.UserControl
    {
        protected DropDownList ddlPageSize;
        protected TextBox tbGotoPage;
        protected Button btnGoto;
        protected Label lblPageCount;
        protected Label lblCurrentPageIndex;
        protected LinkButton lbtnGotoFirstPage;
        protected LinkButton lbtnGotoLastPage;
        protected LinkButton lbtnGotoPrevPage;
        protected LinkButton lbtnGotoNextPage;

        protected override void OnInit(EventArgs e)
        {
            this.Load += new EventHandler(Page_Load);
            base.OnInit(e);
        }       
        public int PageSize
        {
            get
            {
                if (ViewState["PageSize"] == null)
                {
                    ViewState["PageSize"] = 25;
                    try
                    {
                        ViewState["PageSize"] = int.Parse(ddlPageSize.SelectedValue);
                    }
                    catch
                    {
                    }
                }
                return int.Parse(ViewState["PageSize"].ToString());
            }
            private set
            {
                ViewState["PageSize"] = value;
            }
        }

        public int PageIndex
        {
            get
            {
                if (ViewState["PageIndex"] == null)
                    ViewState["PageIndex"] = 0;
                return int.Parse(ViewState["PageIndex"].ToString());
            }
             set
            {
                ViewState["PageIndex"] = value;
            }
        }

        public int RecordCount
        {
            get
            {
                if (ViewState["RecordCount"] == null)
                    ViewState["RecordCount"] = 0;
                return int.Parse(ViewState["RecordCount"].ToString());
            }
            set
            {
                ViewState["RecordCount"] = value;
                ChangeLabel();
            }
        }

        public event PageChangeEventHandler PageChanged;

        protected void Page_Load(object sender, EventArgs e)
        {
            tbGotoPage.Attributes.Add("onkeydown", "if (!checkKey()) return false;");
            btnGoto.Attributes.Add("onclick", "if (!checkPageIndex()) return false;");
            string script = string.Format(@"    <script type=""text/javascript"">
                                                    function checkKey()
		                                            {{
			                                            var keys = new Array(48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 8, 46, 37, 38, 39, 40);
                                            			
			                                            for (var i = 0; i < keys.length; i ++)
			                                            {{
				                                            if (window.event.keyCode == keys[i])
					                                            return true;
			                                            }}
                                            			
			                                            if (window.event.keyCode == 13)
			                                            {{
			                                                document.getElementById(""{0}"").click();
			                                                return false;
			                                            }}
			                                            return false;
		                                            }}
                                            		
    	                                            function checkPageIndex()
		                                            {{

		                                                var pageCount = parseInt(document.getElementById(""{1}"").innerText, 10);
		                                                var index = 1;
		                                                try
		                                                {{
		                                                    index = parseInt(document.getElementById(""{2}"").value, 10);
		                                                }}
		                                                catch (e)
		                                                {{
		                                                    if (document.getElementById(""{2}"").value.length > 0)
		                                                    {{
		                                                        alert(""页码错误"");
		                                                        document.getElementById(""{2}"").focus();
		                                                    }}
		                                                    return false;
		                                                }}
                                            		    
                                            		    
		                                                if (index > 0 && index <= pageCount)
		                                                    return true;
		                                                if (document.getElementById(""{2}"").value.length > 0)
		                                                {{
		                                                    alert(""页码错误"");
		                                                    document.getElementById(""{2}"").focus();
		                                                }}
		                                                return false;
		                                            }}
                                            </script>", btnGoto.ClientID, lblPageCount.ClientID, tbGotoPage.ClientID);
            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"PagerScript", script);


            if (!IsPostBack)
            {



                //记录选过的PageSize
                HttpCookie pageSizeCookie = Request.Cookies["PageSize"];
                if (pageSizeCookie != null && pageSizeCookie.Value != null)
                {
                    int pageSize = Convert.ToInt32(HttpUtility.UrlDecode(pageSizeCookie.Value.ToString()));
                    PageSize = pageSize;
                    ddlPageSize.SelectedValue = pageSize.ToString();
                }
                PageSizeChange();
            }

        }
        protected void lbtnGotoFirstPage_Click(object sender, EventArgs e)
        {
            PageIndex = 0;
            PageSizeChange();
        }
        protected void lbtnGotoPrevPage_Click(object sender, EventArgs e)
        {
            if (PageIndex > 0)
            {
                PageIndex--;
                PageSizeChange();
            }
        }
        protected void lbtnGotoNextPage_Click(object sender, EventArgs e)
        {
            if (PageIndex < RecordCount / PageSize)
            {
                PageIndex++;
                PageSizeChange();
            }
        }
        protected void lbtnGotoLastPage_Click(object sender, EventArgs e)
        {
            PageIndex = RecordCount / PageSize;
            PageSizeChange();
        }
        protected void btnGoto_Click(object sender, EventArgs e)
        {
            try
            {
                PageIndex = int.Parse(tbGotoPage.Text) - 1;
                PageSizeChange();
            }
            catch
            {
                this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "PageIndexError", "<script>alert('页码错误');</script>");
            }

        }
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            tbGotoPage.Text = string.Empty;
            PageSize = int.Parse(ddlPageSize.SelectedValue);
            PageIndex = 0;

            HttpCookie pageSizeCookie = new HttpCookie("PageSize");
            pageSizeCookie.Value = HttpUtility.UrlEncode(ddlPageSize.SelectedValue);
            Response.Cookies.Add(pageSizeCookie);

            PageSizeChange();
        }

        private void PageSizeChange()
        {
            ChangeLabel();

            if (this.PageChanged != null)
                this.PageChanged(this, new EventArgs());
        }

        private void ChangeLabel()
        {
            lblCurrentPageIndex.Text = (PageIndex + 1).ToString();
            if (RecordCount == 0)
                lblPageCount.Text = "1";
            else
                lblPageCount.Text = ((RecordCount + PageSize - 1) / PageSize).ToString();


            if (PageIndex == 0)
            {
                lbtnGotoFirstPage.Enabled = false;
                lbtnGotoPrevPage.Enabled = false;
            }
            else
            {
                lbtnGotoFirstPage.Enabled = true;
                lbtnGotoPrevPage.Enabled = true;
            }

            if (PageIndex >= (RecordCount + PageSize - 1) / PageSize - 1)
            {
                lbtnGotoLastPage.Enabled = false;
                lbtnGotoNextPage.Enabled = false;
            }
            else
            {
                lbtnGotoLastPage.Enabled = true;
                lbtnGotoNextPage.Enabled = true;
            }
        }
    }
}